using Avalonia.Media.Imaging;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace KinonekoSoftware.Foundation.Platform.Graphics
{
    public class ImageProcessorImpl : IPlatformImageProcessor
    {
        public void Release()
        {
            Configuration.Default.MemoryAllocator.ReleaseRetainedResources();
        }
        public void Resize(byte[] buffer, int w, int h, out byte[] array)
        {
            var img = SixLabors.ImageSharp.Image.Load<Rgba32>(buffer);
            var ms  = new MemoryStream(buffer.Length);

            img.Mutate(x => x.Resize(w, h));
            img.SaveAsPng(ms);
            img.Dispose();
            array = ms.ToArray();
            ms.Seek(0, SeekOrigin.Begin);
        }

        public void Crop(byte[] buffer, int x, int y, int w, int h, out byte[] array)
        {
            var img = SixLabors.ImageSharp.Image.Load<Rgba32>(buffer);
            var ms  = new MemoryStream(buffer.Length);

            img.Mutate(c => c.Crop(new Rectangle(x, y, w, h)));
            img.SaveAsPng(ms);
            img.Dispose();
            array = ms.ToArray();
            ms.Seek(0, SeekOrigin.Begin);
        }
    }
}